package jjn.round1;

/**
 * @author Jiang Jining
 * @since 2022-07-24 23:21
 */
public class LeetCode2_AddTwoNumbers {
    
    public static class ListNode {
        int val;
        ListNode next;
        
        ListNode() {
        }
        
        ListNode(int val) {
            this.val = val;
        }
        
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(-1);
        ListNode first = l1;
        ListNode second = l2;
        int next = 0;
        ListNode p = result;
        while (first != null || second != null) {
            int firstVal = 0;
            if (first != null) {
                firstVal = first.val;
            }
            int secondVal = 0;
            if (second != null) {
                secondVal = second.val;
            }
            int temp = firstVal + secondVal + next;
            next = temp / 10;
            temp %= 10;
            p.next = new ListNode(temp);
            p = p.next;
            if (first != null) {
                first = first.next;
            }
            if (second != null) {
                second = second.next;
            }
        }
        if (next != 0) {
            p.next = new ListNode(next);
        }
        return result.next;
    }
}
